import React, { useRef, useState, useEffect } from 'react';
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import type { InputRef, TableColumnsType, TableColumnType, } from 'antd';
import { Button, Input, Space, Table, message ,Alert} from 'antd';
import type { FilterDropdownProps } from 'antd/es/table/interface';
import Highlighter from 'react-highlight-words';
import {  DownloadExcel } from '@/api/SampleClothing';
type DataIndex = keyof DataType;
import '@/styles/test.less'

const Demo = (Props) => {
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef<InputRef>(null);
    const [data, setData] = useState([{ count_num: 0, input_id: 0, name: "", person: "", price: 0, price_sum: 0, total_input: 0, total_output: 0 }])

    const handleSearch = (
        selectedKeys: string[],
        confirm: FilterDropdownProps['confirm'],
        dataIndex: DataIndex,
    ) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };

    const handleReset = (clearFilters: () => void) => {
        clearFilters();
        setSearchText('');
    };

    const getColumnSearchProps = (dataIndex: DataIndex): TableColumnType<DataType> => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
            <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
                <Input
                    ref={searchInput}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
                    style={{ marginBottom: 8, display: 'block' }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
                        icon={<SearchOutlined />}
                        size="small"
                        style={{ width: 90 }}
                    >
                        Search
                    </Button>
                    <Button
                        onClick={() => clearFilters && handleReset(clearFilters)}
                        size="small"
                        style={{ width: 90 }}
                    >
                        Reset
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => {
                            confirm({ closeDropdown: false });
                            setSearchText((selectedKeys as string[])[0]);
                            setSearchedColumn(dataIndex);
                        }}
                    >
                        Filter
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => {
                            close();
                        }}
                    >
                        close
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: (filtered: boolean) => (
            <SearchOutlined style={{ color: filtered ? '#1677ff' : undefined }} />
        ),
        onFilter: (value, record) =>
            record[dataIndex]
                .toString()
                .toLowerCase()
                .includes((value as string).toLowerCase()),
        onFilterDropdownOpenChange: (visible) => {
            if (visible) {
                setTimeout(() => searchInput.current?.select(), 100);
            }
        },
        render: (text) =>
            searchedColumn === dataIndex ? (
                <Highlighter
                    highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                    searchWords={[searchText]}
                    autoEscape
                    textToHighlight={text ? text.toString() : ''}
                />
            ) : (
                text
            ),
    });

    const columns = [
        {
            title: '入库ID',
            dataIndex: 'input_id',
            key: 'input_id',
            //   width: '20%',
            sorter: (a, b) => a.input_id - b.input_id,
            ...getColumnSearchProps('input_id'),
            //   sorter: (a, b) => a.address.length - b.address.length,
            //   sortDirections: ['descend', 'ascend'],
        },
        {
            title: '品名',
            dataIndex: 'name',
            key: 'name',
            //   width: '30%',
            ...getColumnSearchProps('name'),
        },
        {
            title: '单价',
            dataIndex: 'price',
            key: 'price',
            sorter: (a, b) => a.price - b.price,
            // width: '20%',
            ...getColumnSearchProps('price'),
        },
        {
            title: '入库数',
            dataIndex: 'total_input',
            key: 'total_input',
            // width: '20%',
            ...getColumnSearchProps('total_input'),
        },
        {
            title: '出库数',
            dataIndex: 'total_output',
            key: 'total_output',
            // width: '20%',
            ...getColumnSearchProps('total_output'),
        },
        {
            title: '库存量',
            dataIndex: 'count_num',
            key: 'count_num',
            // render: (text, record, index) => {
            //     // console.log("text, record, index",text, record, index)
            //     // 当count_num小于0时，返回一个带有红色样式的span元素  
            //     if (text < 0) {
            //         return <span style={{ color: 'red', fontWeight: 600 }}>{text}</span>;
            //     }
            //     // 否则，直接返回文本  
            //     return text;
            // },
            sorter: (a, b) => a.count_num - b.count_num,
            // width: '30%',
            // ...getColumnSearchProps('count_num'),
        },
        {
            title: '总金额',
            dataIndex: 'price_sum',
            key: 'price_sum',
            // render: (text, record, index) => {
            //     // console.log("text, record, index",text, record, index)
            //     // 当count_num小于0时，返回一个带有红色样式的span元素  
            //     if (text < 0) {
            //         return <span style={{ color: 'red', fontWeight: 600 }}>{text}</span>;
            //     }
            //     // 否则，直接返回文本  
            //     return text;
            // },
            // width: '20%',
            // ...getColumnSearchProps('price_sum'),
        },
        {
            title: '买版人',
            dataIndex: 'person',
            key: 'person',
            ...getColumnSearchProps('person'),
        },
    ];
    const DownloadViews = async () => {
        try {
            const reponse = await DownloadExcel({ 'file': 'views' });
            // console.log(reponse);
            const blob = new Blob([reponse], { type: 'application/octet-stream' });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            const now = new Date();
            const formattedTime = now.toISOString().slice(0, 10).replace(/-/g, '_') + '_' + now.toTimeString().slice(0, 5).replace(/:/g, '_');
            link.setAttribute('download', `${formattedTime}_库存表.xlsx`);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            message.success("下载成功");
        } catch (err) {
            message.error('下载失败');
        }
    }
    const rowClassName = ({ count_num }) => {  
        if (count_num < 0) {  
          return 'negative-row'; // 返回一个 CSS 类名  
        }  
        return ''; // 默认情况下不添加任何类名  
      };  
    useEffect(() => {
        setData(Props.Props);
    }, [Props]);
    return (
        <>
            <Space style={{ margin:'auto',marginTop: '10px',marginBottom: '10px' }}>
                <Button
                    type="primary"
                    style={{ backgroundColor: '#35970f', color: "#fff" }}
                    icon={<DownloadOutlined />}
                    onClick={DownloadViews}
                >
                    点击下载库存数据（全部）
                </Button>
                <Alert message="库存小于 0 时 ,显示 浅绿背景 字体红色 高亮" type="error" style={{}} />
            </Space>
            <Table
                columns={columns}
                dataSource={data}
                rowClassName={rowClassName}
            />

        </>

    );
};

export default Demo;